<?php
/**
 * Created by PhpStorm.
 * User: kongqi
 * Date: 2019/10/25
 * Time: 17:23
 */

namespace App\Plugin\HostServer\Front;

use App\Plugin\HostServer\Models\PnHostSvCode;
use App\Plugin\HostServer\Models\PnHostSvUser;
use App\Plugin\HostServer\Models\PnHostSvUserLog;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

use Laravel\Socialite\Facades\Socialite;
use Illuminate\Validation\ValidationException;
use Session;

class AuthController extends BaseController
{

    use ThrottlesLogins;

    public $guard = 'host_server';
    public $route_default = 'hostserver';
    public $table_name = 'pn_host_sv_users';

    public function backHome()
    {
        return redirect()->route('plugin.' . $this->route_default . '.user');
    }

    public function login()
    {
        if (user('', $this->guard)) {
            return $this->backHome();
        }
        $data = [];
        $title = '会员登录';
        $this->setSeo($title, $title, $title);
        return $this->display($data);
    }

    //忘记密码
    public function forget()
    {
        $title = '忘记密码';
        $this->setSeo($title, $title, $title);
        return $this->display();
    }


    //提交注册或登录
    public function auth(Request $request)
    {
        $type = $request->input('type');
        if (empty($type)) {
            return redirect()->back()->with(['message' => '没有选择登录类型']);
        }
        if ($type == 'login') {
            return $this->postLogin($request);
        } elseif ($type == 'regist') {
            return $this->postRegist($request);
        } elseif ($type == 'forget') {
            return $this->postForget($request);
        }

    }

    //提交忘记密码
    public function postForget($request)
    {

        $this->validateEmail($request);

        $email = $request->input('email');
        $password = $request->input('password');
        $has = PnHostSvUser::where('email', $email)->first();
        if (empty($has)) {
            return back()
                ->withInput($request->only('email'))
                ->withErrors(['email' => '邮箱不存在']);
        }

        //更新验证码1
        PnHostSvCode::codeUpdate('email',$email);

        //重设密码
        $user=PnHostSvUser::where('email',$email)->first();
        if(empty($user))
        {
            return back()->withErrors(['email'=>'邮箱不存在']);
        }
        $user->password=$password;
        $r=$user->save();
        if($r)
        {
            return redirect()->route('plugin.hostserver.user');
        }
        return back()->withErrors(['email'=>'修改密码失败']);

    }

    //忘记密码表单验证
    protected function validateEmail(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => ['required', 'string', 'min:6', 'confirmed'],
            'code' => function ($attribute, $value, $fail) {
                if ($value != PnHostSvCode::checkCode($value, 'email', \request()->input('email'))) {
                    $fail( '验证码无效');
                }
            }
        ],[],['code'=>'验证码']);

    }


    //操作权限的认证组
    protected function guard()
    {
        return Auth::guard($this->guard);
    }

    protected function validateLogin(Request $request)
    {
        $request->validate([
            'email' => 'required|string',
            'password' => 'required|string',
        ]);
    }

    public function username()
    {
        return 'email';
    }

    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }

    protected function attemptLogin(Request $request)
    {
        $login = [
            'email' => $request->input('email'),
            'password' => $request->input('password'),

        ];
        return $this->guard()->attempt(
            $login, $request->input('remember')
        );
    }

    protected function sendLoginResponse(Request $request)
    {
        //生成新的session
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user());
    }

    public function checkUser($user)
    {
        if ($user['is_checked'] == 0) {
            //退出
            $this->guard()->logout();
            session()->invalidate();
            return $this->returnError(401, '账号被禁用', nroute('plugin.' . $this->route_default . '.login'));
        }
    }

    //登录成功跳转
    protected function authenticated(Request $request, $user)
    {
        //判断是否被禁用
        //dd($user->is_checked);

        if ($user['is_checked'] == 0) {
            //退出
            $this->guard()->logout();
            $request->session()->invalidate();
            return $this->returnError(401, '账号被禁用', nroute('plugin.' . $this->route_default . '.login'));
        }

        $back = nroute('plugin.hostserver.user');

        $user->save();//保存本次提交
        //记录登录日志
        PnHostSvUserLog::add('login','登录',$user->id);

        return redirect()->intended($back);

    }

    //提交登录
    public function postLogin($request)
    {

        $this->validateLogin($request);

        if (method_exists($this, 'hasTooManyLoginAttempts') &&
            $this->hasTooManyLoginAttempts($request)) {

            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    protected function sendFailedLoginResponse(Request $request)
    {
        throw ValidationException::withMessages([
            $this->username() => ['账号或密码不正确'],
        ]);
    }

    public function postRegist($request)
    {
        $this->registValidator($request->all())->validate();

        $user = $this->create($request->all());
        $this->guard()->login($user);
        //更新验证码1
        PnHostSvCode::codeUpdate('email',$user->email);
        return $this->authenticated($request, $user);
    }

    //创建会员
    protected function create(array $data)
    {
        return PnHostSvUser::regist($data);
    }

    /**
     * 注册验证
     * @param array $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function registValidator(array $data)
    {
        return Validator::make($data, [
            'email' => ['required', 'string', 'email', 'max:255', 'unique:' . $this->table_name],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
            'buy_password' => ['required', 'string', 'min:6'],
            'name' => ['required', 'string'],
            'code' => function ($attribute, $value, $fail) {
                if ($value != PnHostSvCode::checkCode($value, 'email', \request()->input('email'))) {
                    $fail('验证码无效');
                }
            }
        ], [], [
            'buy_password' => '交易密码'
        ]);
    }

    public function regist()
    {
        if (user('', $this->guard)) {
            return $this->backHome();
        }

        $data = [];
        $title = '会员注册';
        $this->setSeo($title, $title, $title);
        return $this->display($data);
    }


    public function loginOut(Request $request)
    {
        Auth::guard($this->guard)->logout();

        $request->session()->invalidate();

        return redirect()->route('plugin.' . $this->route_default . '.login');
    }


}